from .base import db
from datetime import datetime
import os

class CertificateAttachment(db.Model):
    __tablename__ = 'certificate_attachments'
    id = db.Column(db.Integer, primary_key=True)
    certificate_id = db.Column(db.Integer, nullable=False)
    filename = db.Column(db.String(255), nullable=False)
    filesize = db.Column(db.Integer, nullable=False)
    filetype = db.Column(db.String(100))
    description = db.Column(db.String(255))
    filepath = db.Column(db.String(500), nullable=False)
    upload_time = db.Column(db.DateTime, default=datetime.utcnow)
    uploader = db.Column(db.String(100), default='系统')

    def to_dict(self):
        return {
            'id': self.id,
            'certificate_id': self.certificate_id,
            'filename': self.filename,
            'filesize': self.filesize,
            'filetype': self.filetype,
            'description': self.description,
            'upload_time': self.upload_time.isoformat() if self.upload_time else None,
            'uploader': self.uploader
        }

    @classmethod
    def get_path(cls, instance=None, filename=None):
        upload_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../uploads/certificates')
        if not os.path.exists(upload_dir):
            os.makedirs(upload_dir)
        if instance and instance.id:
            return os.path.join(upload_dir, f"{instance.id}_{filename}")
        else:
            timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
            return os.path.join(upload_dir, f"{timestamp}_{filename}") 